package com.bjut.vendormgrsys.support.filter.jwt;

import com.bjut.vendormgrsys.util.JsonUtils;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public interface IJwtFilter {

    @SuppressWarnings("deprecation")
    default void response(HttpServletResponse response, int status, String message, String id) {
        try {
            response.addHeader("Authorization", id);
            Cookie cookie = new Cookie("authorization_cookie", id);
            cookie.setPath("/");
            cookie.setSecure(true);
            cookie.setHttpOnly(true);
            //登录成功时，返回json格式进行提示
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.setStatus(status);
            Map<String, Object> map = new HashMap<>(4);
            map.put("code", status);
            map.put("message", message);
            if (StringUtils.hasLength(id)) {
                map.put("authorization", id);
            }
            PrintWriter out = response.getWriter();
            out.write(JsonUtils.toString(map));
            out.flush();
            out.close();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
}
